package com.ebt.m.proposal_v2.ui.view;

import android.content.Context;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.customer.ui.DialogCustomerChoose;
import com.ebt.m.customer.view.ConfirmDialog;
import com.ebt.m.data.entity.Customer;
import com.ebt.m.proposal_v2.bean.ApplicantEntity;
import com.ebt.m.proposal_v2.bean.InsuredEntity;
import com.ebt.m.proposal_v2.ui.MakeProposalActivity;
import com.ebt.m.proposal_v2.utils.DataUtils;
import com.ebt.m.proposal_v2.utils.InsuredCheckUtils;
import com.ebt.m.proposal_v2.utils.RxUtils;
import com.ebt.m.proposal_v2.widget.base.CompatLinearLayout;
import com.ebt.m.proposal_v2.widget.view.InsuranceCellView;
import com.ebt.m.proposal_v2.widget.view.ProposalHeader;
import com.ebt.m.proposal_v2.widget.view.ProposalPerson;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.utils.android.DateUtils;

import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;

/**
 * 投保人UI
 * <p>
 * 保存客户流程：
 * 1、 默认进入为选中
 * 2、 列表导入要消失
 * 3、 导入后，编辑非姓名选项会显现
 * 4、 点击，自由切换
 *
 * @author archer.qi
 *         Created on 2017/5/9.
 */
public class ApplicantView extends CompatLinearLayout {

    @BindView(R.id.applicant_header)
    ProposalHeader proposalHeader;
    @BindView(R.id.applicant_person)
    ProposalPerson proposalPerson;
    @BindView(R.id.applicant_customer)
    LinearLayout proposalCustomer;
    @BindView(R.id.applicant_saveCustomerImg)
    ImageView proposalCustomerImg;
    @BindView(R.id.applicant_saveCustomerDes)
    TextView proposalCustomerDes;

    private FragmentManager fragmentManager;
    private DialogCustomerChoose importCustomerDialog;
    private boolean allowSaveToCustomerList; // 是否需要将变更保存到客户列表
    private OnApplicantChangedListener mListener;

    public ApplicantView(Context context) {
        super(context);
    }

    public ApplicantView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected int setContentView() {
        return R.layout.proposal_v2_applicant;
    }

    @Override
    protected void onBindView() {
        proposalPerson.setInsured(false);
        proposalHeader.setTitle(R.string.proposalTitleApplicant);
        proposalHeader.showRight();
        proposalHeader.addImportCustomerListener(view -> importCustomer());
        proposalHeader.setHelperView(true);

        RxUtils.click(proposalCustomer, view -> toggleCustomerSave());

        /**
         * 新建计划书，默认显示保存到客户列表选项，并选中
         * 从客户列表导入，隐藏保存到客户列表选项
         * 导入后，更新除Name之外的其他字段，重新显示保存选项
         */
        proposalPerson.setInfoChangedListener(new ProposalPerson.onInfoChangedListener() {
            @Override
            public void onInfoChanged() {
                allowSaveToCustomerList = false;
//                toggleCustomerSave();
                if (mListener != null) {
                    mListener.onApplicantChanged();
                }
            }
        });
    }

    /**
     * 切换是否保存到客户列表
     */
    private void toggleCustomerSave() {
        allowSaveToCustomerList = !allowSaveToCustomerList;
        proposalCustomerImg.setImageResource(
                allowSaveToCustomerList ? R.drawable.ic_checked_circle : R.drawable.ic_uncheck_circle);
    }

    public void setCustomerSave(boolean allow) {
        allowSaveToCustomerList = allow;
        proposalCustomerImg.setImageResource(
                allowSaveToCustomerList ? R.drawable.ic_checked_circle : R.drawable.ic_uncheck_circle);
    }

    /**
     * 是否显示客户保存模块
     *
     * @param shown
     */
    public void showCustomerSave(boolean shown) {
        allowSaveToCustomerList = shown;
        proposalCustomer.setVisibility(shown ? VISIBLE : GONE);
    }

    /**
     * 导入客户
     */
    private void importCustomer() {
        if (importCustomerDialog == null) {
            importCustomerDialog = DialogCustomerChoose.newInstance(getString(R.string.pro_choose_customer),
                    new DialogCustomerChoose.CustomerChooseListener() {
                        @Override
                        public void onPick(Customer customer) {
                            checkNewCustomer(customer);
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
        }
        importCustomerDialog.show(fragmentManager, "DialogCustomerChoose");
    }

    private void checkNewCustomer(Customer customer) {
        if (getContext() instanceof MakeProposalActivity) {
            InsuredView insuredView = ((MakeProposalActivity) getContext()).getMyselfInsuredView();
            if (insuredView != null) {
                //需要检测
                final InsuredEntity insuredEntityTemp = new InsuredEntity();
                insuredEntityTemp.name = customer.getName();
                insuredEntityTemp.sex = customer.getSex();
                insuredEntityTemp.age = customer.getAge();
                if (customer.getIsConfirm() != 0) {
                    insuredEntityTemp.birthday = DateUtils.dateTime2String(customer.getBirthday());
                }
                insuredEntityTemp.profession = 1;

                ArrayList<Object> ret = InsuredCheckUtils.checkChangeAccordWithInsuranceLimit(true, insuredView, insuredEntityTemp, InsuranceCellView.CHECK_TYPE_AGE);
                if (!(Boolean) ret.get(0)) {
                    showConfirmChangeDialog("导入的客户不符合被保条件，是否继续更改？", "更改", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            InsuranceView insuranceView = insuredView.getCorrespondingInsuranceView();
                            ArrayList<InsuranceCellView> list = insuranceView.getInsuranceCellViews();
                            for (InsuranceCellView cellView : list) {
                                InsuredEntity insuredEntity = InsuredCheckUtils.getApplicantAsInsuredEntity(true, insuredEntityTemp, insuranceView, cellView);
                                cellView.setInsuredEntity(insuredEntity);
                            }
                            finishAddCustomer(customer);
                        }
                    });
                } else {
                    InsuranceView insuranceView = insuredView.getCorrespondingInsuranceView();
                    ArrayList<InsuranceCellView> list = insuranceView.getInsuranceCellViews();
                    for (InsuranceCellView cellView : list) {
                        InsuredEntity insuredEntity = InsuredCheckUtils.getApplicantAsInsuredEntity(true, insuredEntityTemp, insuranceView, cellView);
                        cellView.setInsuredEntity(insuredEntity);
                    }
                    finishAddCustomer(customer);
                }
                return;
            }
        }

        finishAddCustomer(customer);
    }

    private void finishAddCustomer(Customer customer){
        if (customer != null) {
            Date birthday = customer.getBirthday();
            if (customer.getIsConfirm() == 0) {
                customer.setAge(DateUtils.getAge(birthday));
                customer.setBirthday(null);
            }
            customer.cloneToOriginName();
            proposalPerson.setCustomer(customer);
            allowSaveToCustomerList = true;
            toggleCustomerSave();
            if (mListener != null) {
                mListener.onApplicantChanged();
            }
        }
    }



    /*************************我是友好的分割线，以下是调用方法**********************/

    /**
     * 导入客户必须的对象
     *
     * @param manager
     */
    public ApplicantView supportFragmentManager(FragmentManager manager) {
        this.fragmentManager = manager;
        if (proposalPerson != null) {
            proposalPerson.setFragmentManager(fragmentManager);
        }
        return this;
    }

    /**
     * 是否需要保存到客户列表
     * <b>
     * 如果需要，在制作计划书时保存最新用户信息到服务器
     * </b>
     *
     * @return
     */
    public boolean allowSaveToCustomerList() {
        return allowSaveToCustomerList;
    }

    /**
     * 隐藏提示
     */
    public void hideTipView() {
        proposalHeader.hideHelperView();
    }

    /**
     * 为了便于直接绑定或取出数据，采用Customer与ApplicantEntity的方式保存数据
     * 两者在相应的字段数据信息一致，根据需求自取
     */

    /**
     * 取出数据
     *
     * @return
     */
    public Customer getCustomer() {
        return proposalPerson.getCustomer();
    }

    /**
     * 取出数据
     *
     * @return
     */
    public ApplicantEntity getApplicant() {
        return DataUtils.toApplicant(proposalPerson.getCustomer());
    }

    /**
     * 绑定数据
     *
     * @param applicant
     */
    public void bindData(ApplicantEntity applicant) {
        if (applicant != null) {
            proposalPerson.setCustomer(DataUtils.toCustomer(applicant));
        }
    }

    /**
     * 绑定数据
     *
     * @param customer
     */
    public void bindData(Customer customer) {
        if (customer != null) {
            proposalPerson.setCustomer(customer);
        }
    }

    /**
     * 检测
     *
     * @return
     */
    public boolean check() {
        String applicantName = proposalPerson.getName();
        if (TextUtils.isEmpty(applicantName)) {
            UIHelper.makeToast(getViewContext(), "请填写投保人姓名");
            return false;
        }
        return true;
    }

    /**
     * 投保人信息变更监听
     *
     * @param listener
     */
    public void setOnApplicantChangedListener(OnApplicantChangedListener listener) {
        mListener = listener;
    }

    public interface OnApplicantChangedListener {
        void onApplicantChanged();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (proposalPerson != null && insuredView != null){
            proposalPerson.setCorrespondInsuredView(insuredView);
        }
    }
    private InsuredView insuredView;
    public void setCorrespondingInsuredView(InsuredView insuredView){
        this.insuredView = insuredView;
        if (proposalPerson != null){
            proposalPerson.setCorrespondInsuredView(this.insuredView);
        }
    }

    private ConfirmDialog confirmDialog;
    private void showConfirmChangeDialog(String message, String positiveButtonText, View.OnClickListener listener) {
        if (confirmDialog == null) {
            confirmDialog = new ConfirmDialog(getContext());
        }
        if (confirmDialog.isShowing()) {
            confirmDialog.dismiss();
        }
        confirmDialog.setMessage(message);
        confirmDialog.setPositiveButton(positiveButtonText, new OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onClick(view);
                confirmDialog.dismiss();
            }
        });
        confirmDialog.show();
    }
}
